<template>
  <div class="app-container" v-loading="loading">
    <div style="background-color: #fff">
      <div class="container-module" style="padding-bottom: 0">
        <el-form :inline="true" class="search-form" size="small">
          <el-row style="display: flex">
            <div style="flex: 1">
              <el-form-item
                class="search-form-item"
                label="收货人"
                style="margin: 5px 0"
              >
                <el-input
                  clearable
                  placeholder="请输入收货人姓名"
                  v-model="searchForm.recipient"
                  type="text"
                  min="1"
                  class="input-with-select"
                >
                </el-input>
              </el-form-item>
              <el-form-item
                class="search-form-item"
                label="联系电话"
                style="margin: 5px 0"
              >
                <el-input
                  clearable
                  placeholder="请输入手机号"
                  v-model="searchForm.phone_number"
                  type="text"
                  min="1"
                  class="input-with-select"
                >
                </el-input>
              </el-form-item>

              <el-form-item
                v-show="isExpand"
                class="search-form-item"
                label="省份"
                style="margin: 5px 0"
              >
                <el-select
                  @change="provinceWay"
                  v-model="searchForm.province_id"
                  placeholder="请选择省份"
                >
                  <el-option
                    v-for="item in provinceList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item
                v-show="isExpand"
                class="search-form-item"
                label="城市"
                style="margin: 5px 0"
              >
                <el-select
                  :disabled="cityList.length == 0"
                  @change="cityWay"
                  v-model="searchForm.city_id"
                  placeholder="请选择城市(请先选择省份)"
                >
                  <el-option
                    v-for="item in cityList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item
                v-show="isExpand"
                class="search-form-item"
                label="请选择区县"
                style="margin: 5px 0"
              >
                <el-select
                  :disabled="districtList.length == 0"
                  v-model="searchForm.district_id"
                  placeholder="请选择区县(请先选择城市)"
                >
                  <el-option
                    v-for="item in districtList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>

              <el-form-item
                class="search-form-item"
                label="是否默认"
                style="margin: 5px 0"
              >
                <el-select
                  style="width: 100%"
                  clearable
                  v-model="searchForm.is_default"
                  filterable
                  placeholder="请选择是否默认"
                >
                  <el-option
                    v-for="item in [
                      { id: '1', name: '默认' },
                      { id: '2', name: '非默认' },
                    ]"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </div>
            <div style="padding: 5px 0">
              <el-form-item>
                <el-button
                  size="small"
                  type="primary"
                  icon="el-icon-search"
                  @click="getListWay"
                  >查询</el-button
                >
                <el-button
                  size="small"
                  icon="el-icon-refresh"
                  type="primary"
                  @click="resetting"
                  >重置</el-button
                >
              </el-form-item>
              <el-button
                size="small"
                style="margin-top: 1px"
                type="warning"
                :icon="isExpand ? 'el-icon-caret-top' : 'el-icon-caret-bottom'"
                @click="isExpand = !isExpand"
                >{{ isExpand ? "收起" : "展开" }}</el-button
              >
            </div>
          </el-row>
        </el-form>
      </div>
      <el-divider></el-divider>
      <div style="padding: 0 20px 20px">
        <div class="marginBottom">
          <el-row :gutter="20">
            <el-col :span="20">
              <el-button
                @click="addWay"
                v-hasPermi="'shippingaddress/add'"
                icon="el-icon-circle-plus-outline"
                type="primary"
                >添加地址</el-button
              >
            </el-col>
            <el-col :span="4" style="float: right">
              <div class="right-panel el-button-group">
                <el-button
                  class=""
                  icon="el-icon-refresh"
                  size="mini"
                  @click="getListWay"
                ></el-button>
                <el-dropdown trigger="click" :hide-on-click="false">
                  <span class="el-dropdown-link">
                    <el-button
                      class=""
                      icon="el-icon-s-operation"
                      size="mini"
                    ></el-button>
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item
                      v-for="fruit in allTableThead"
                      :key="fruit"
                    >
                      <el-checkbox
                        v-model="checkboxTableThead"
                        :label="fruit"
                        >{{ tableTheadOptions[fruit].label }}</el-checkbox
                      >
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </div>
            </el-col>
          </el-row>
        </div>
        <el-row :gutter="20">
          <el-col class="new_table_card">
            <el-table
              highlight-current-row
              :data="AddressList"
              :header-cell-style="{
                'background-color': '#f3f8fe',
                color: '#606266',
                height: '50px',
              }"
              style="width: 100%"
              v-loading="loading"
            >
              <el-table-column
                v-for="fruit in tableThead"
                :key="fruit"
                :label="tableTheadOptions[fruit].label"
                min-width="80"
                align="center"
              >
                <template slot-scope="scope">
                  <div v-if="fruit == 'is_default'">
                    <div v-if="scope.row[fruit] == 1" size="mini">是</div>
                    <div v-if="scope.row[fruit] == 2" size="mini">否</div>
                  </div>
                  <div v-else-if="fruit == 'province_name'">
                    {{ scope.row.province_name }}
                    {{ scope.row.city_name }}
                    {{ scope.row.district_name }}
                  </div>
                  <span v-else>
                    {{ scope.row[fruit] }}
                  </span>
                </template>
              </el-table-column>

              <el-table-column
                align="center"
                fixed="right"
                width="200"
                prop="address"
                label="操作"
              >
                <template slot-scope="scope">
                  <el-button

                    type="text"
                    v-hasPermi="'shippingaddress/edit'"

                    @click="editWay(scope.row)"
                  >
                    编辑
                  </el-button>
                  <el-popconfirm
                    title="这是一段内容确定删除吗？"
                    @confirm="delWay(scope.row)"
                  >
                    <el-button
                      v-hasPermi="'shippingaddress/del'"
                      style="margin-left: 10px"
                      type="text"

                      slot="reference"
                    >
                      删除
                    </el-button>
                  </el-popconfirm>
                </template>
              </el-table-column>
            </el-table></el-col
          >
        </el-row>
        <el-row style="text-align: right">
          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="searchForm.page"
            :limit.sync="searchForm.pageSize"
            @pagination="getListWay"
          />
        </el-row>
      </div>
    </div>

    <el-drawer
      :modal-append-to-body="false"
      :append-to-body="true"
      title="退货地址"
      size="50%"
      :withHeader="false"
      :visible.sync="addressDialog"
      @close="addressClose"
      :show-close="true"
    >
      <div style="position: relative; height: 100%" v-loading="addressLoading">
        <div class="drawerTitle">
          <span>退货地址</span>
          <div class="close" @click="addressClose">
            <i class="el-icon-close" style="font-size:22px"></i>
          </div>
        </div>

        <div class="secondTitle">
          <i style="color: rgb(0, 82, 217)" class="el-icon-info"></i>
          <span
            >用于平台介入售后，退换货管理时，可已使用这里添加的快捷退货地址！</span
          >
        </div>

        <div class="informationTitleView">
          <div class="leftBox">
            <div class="leftborder"></div>
            <div class="text">地址信息</div>
          </div>
          <div class="right"></div>
        </div>
        <el-form
          ref="addressForm"
          :rules="addressRules"
          :model="addressForm"
          label-width="120px"
        >
          <!-- <el-row :gutter="20" style="display: flex; flex-wrap: wrap">
            <el-col :span="11">
              <el-form-item label="收货人" prop="recipient">
                <el-input
                  maxlength="10"
                  show-word-limit
                  v-model="addressForm.recipient"
                  placeholder="请输入收货人"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="收货人手机号" prop="phone_number">
                <el-input
                  maxlength="11"
                  show-word-limit
                  v-model="addressForm.phone_number"
                  placeholder="请输入收货人手机号"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="省份" prop="province_id">
                <el-select
                  @change="provinceWay"
                  v-model="addressForm.province_id"
                  placeholder="请选择省份"
                >
                  <el-option
                    v-for="item in provinceList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="城市" prop="city_id">
                <el-select
                  :disabled="cityList.length == 0"
                  @change="cityWay"
                  v-model="addressForm.city_id"
                  placeholder="请选择城市(请先选择省份)"
                >
                  <el-option
                    v-for="item in cityList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="区/县" prop="district_id">
                <el-select
                  :disabled="districtList.length == 0"
                  v-model="addressForm.district_id"
                  placeholder="请选择区县(请先选择城市)"
                >
                  <el-option
                    v-for="item in districtList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="详细地址" prop="address_details">
                <el-input
                  maxlength="50"
                  show-word-limit
                  v-model="addressForm.address_details"
                  placeholder="请输入详细地址"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="是否为默认地址" prop="is_default">
                <el-radio-group v-model="addressForm.is_default">
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="2">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col> -->
          <el-form-item label="收货人" prop="recipient">
            <el-input
              maxlength="10"
              show-word-limit
              v-model="addressForm.recipient"
              placeholder="请输入收货人"
              size="medium"
              class="addressInput"
            ></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="phone_number">
            <el-input
              maxlength="11"
              show-word-limit
              v-model="addressForm.phone_number"
              placeholder="请输入收货人手机号"
              size="medium"
              class="addressInput"
            ></el-input>
          </el-form-item>
          <el-form-item label="省" prop="province_id">
            <el-select
              @change="provinceWay"
              v-model="addressForm.province_id"
              placeholder="请选择省份"
              size="medium"
              class="addressInput"
            >
              <el-option
                v-for="item in provinceList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="城市" prop="city_id">
            <el-select
              size="medium"
              class="addressInput"
              :disabled="cityList.length == 0"
              @change="cityWay"
              v-model="addressForm.city_id"
              placeholder="请选择城市(请先选择省份)"
            >
              <el-option
                v-for="item in cityList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="区/县" prop="district_id">
            <el-select
              size="medium"
              class="addressInput"
              :disabled="districtList.length == 0"
              v-model="addressForm.district_id"
              placeholder="请选择区县(请先选择城市)"
            >
              <el-option
                v-for="item in districtList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="详细地址" prop="address_details">
            <el-input
              size="medium"
              class="addressInput"
              maxlength="50"
              show-word-limit
              v-model="addressForm.address_details"
              placeholder="请输入详细地址"
            ></el-input>
          </el-form-item>

          <el-form-item label="是否默认" prop="is_default">
            <el-radio-group v-model="addressForm.is_default">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="2">否</el-radio>
            </el-radio-group>
          </el-form-item>

          <div class="btnGroup">
            <el-button :loading="addressLoading" @click="addressDialog = false"
              >取 消</el-button
            >
            <el-button
              :loading="addressLoading"
              type="primary"
              @click="addressSubmit('form')"
              >保 存</el-button
            >
          </div>
        </el-form>
      </div>
    </el-drawer>
  </div>
</template>

  <script>
import { getRegionList } from "@/api/user/index";
import { querySupplierList, getInfo } from "@/api/index";
import {
  getplatformAddressList,
  SaveplatformAddress,
  delplatformAddress,
  geplatformAddressInfo,
} from "@/api/commodity/index";
const tableTheadOption = {
  id: {
    label: "ID",
    field: "id",
  },
  recipient: {
    label: "收货人名称",
    field: "recipient",
  },
  phone_number: {
    label: "手机号",
    field: "phone_number",
  },
  province_name: {
    label: "省市区",
    field: "province_name",
  },
  address_details: {
    label: "详细地址",
    field: "address_details",
  },
  is_default: {
    label: "是否默认",
    field: "is_default",
  },
};
const allTableThead = [
  "id",
  "recipient",
  "phone_number",
  "province_name",
  "address_details",
  "is_default",
];
const defaultTableThead = [
  "id",

  "recipient",
  "phone_number",
  "province_name",
  "address_details",
  "is_default",
];
export default {
  watch: {
    checkboxTableThead(valArr) {
      this.tableThead = this.allTableThead.filter(
        (i) => valArr.indexOf(i) >= 0
      );
      this.tableKey = this.tableKey + 1;
    },
  },
  data() {
    return {
      // 默认表头
      tableTheadOptions: tableTheadOption,
      allTableThead: allTableThead,
      tableThead: defaultTableThead, // 默认表头
      checkboxTableThead: defaultTableThead, // 默认表头值
      tableKey: 1, // 为了保证table 每次都会重渲
      loading: false,
      userInfo: {}, // 用户信息
      administrators: false, // 当前登录用户是否是管理员
      SupplierList: [], // 供应商列表
      provinceList: [], // 省份列表
      cityList: [], // 城市列表
      districtList: [], // 区县列表
      searchForm: {
        // supplier_id: "", // 供应商id
        recipient: "", // 收货人姓名
        phone_number: "", // 手机号
        is_default: "", // 是否默认 1默认 2不默认
        province_id: "", // 类型 1省 2市 3区
        city_id: "", // 值
        district_id: "", // 值
        page: 1,
        pageSize: 10,
      },
      total: 0,
      AddressList: [],
      title: "添加地址",
      addressForm: {
        recipient: "",
        phone_number: "",
        province_id: "",
        city_id: "",
        district_id: "",
        address_details: "",
        is_default: 2,
        id: "",
        // supplier_id: "",
      },

      addressRules: {
        // supplier_id: [
        //   {
        //     required: true,
        //     validator: (rule, value, callback) => {
        //       if (value === "") {
        //         return callback(new Error("供货商id不能为空"));
        //       }
        //       callback();
        //     },
        //     trigger: "change",
        //   },
        // ],
        recipient: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (value === "") {
                return callback(new Error("请填写收货人姓名"));
              }
              var reg = /[^a-zA-Z\u4e00-\u9fa5]/g;
              if (reg.test(value)) {
                return callback(new Error("姓名中不能带有特殊字符"));
              }
              callback();
            },
            trigger: "change",
          },
        ],
        phone_number: [
          {
            required: true,
            validator: (rule, value, callback) => {
              var reg = /^1[3456789]\d{9}$/;
              if (!reg.test(value)) {
                return callback(new Error("手机号格式不正确"));
              }
              callback();
            },
            trigger: "change",
          },
        ],
        province_id: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (value === "") {
                return callback(new Error("请选择省份"));
              }
              callback();
            },
            trigger: "change",
          },
        ],
        city_id: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (value === "") {
                return callback(new Error("请选择城市"));
              }
              callback();
            },
            trigger: "change",
          },
        ],
        district_id: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (value === "") {
                return callback(new Error("请选择区县"));
              }
              callback();
            },
            trigger: "change",
          },
        ],
        address_details: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (value === "") {
                return callback(new Error("请输入详细地址"));
              }
              callback();
            },
            trigger: "change",
          },
        ],
      },
      addressDialog: false,
      addressLoading: false,

      isExpand: false, //是否展开搜索
    };
  },
  created(args) {
    var _this = this;
    _this.loading = true;
    let p1 = new Promise((req, rej) => {
      if (localStorage.getItem("region")) {
        var regions = JSON.parse(localStorage.getItem("region"));
        _this.provinceList = regions;
        req();
      } else {
        getRegionList().then((res) => {
          if (res.code !== 200 || res.status !== 1) {
            this.$messages.error(res.msg);
            rej();
          }
          // localStorage.setItem(
          //   "getregionlist",
          //   JSON.stringify(res.data)
          // );
          _this.provinceList = res.data;
          req();
        });
      }
    });
    let p2 = new Promise((req, rej) => {
      querySupplierList().then((res) => {
        if (res.code !== 200 || res.status !== 1) {
          this.$messages.error(res.msg);
          rej();
        }
        _this.SupplierList = res.data;
        req();
      });
    });
    // let p3 = new Promise((req, rej) => {
    //   getInfo().then((res) => {
    //     if (res.code !== 200 || res.status !== 1) {
    //       this.$messages.error(res.msg);
    //       rej();
    //     }
    //     _this.userInfo = res.data;
    //     if (_this.userInfo.supplier_id == 0 || _this.userInfo.supplier_id) {
    //       _this.administrators = true;
    //       console.log("11");
    //     } else {
    //       _this.administrators = false;
    //       _this.searchForm.supplier_id = _this.userInfo.supplier_id;
    //       _this.addressForm.supplier_id = _this.userInfo.supplier_id;
    //     }

    //     req();
    //   });
    // });
    Promise.all([p1, p2])
      .then((res) => {
        this.getListWay();
      })
      .catch(() => {
        _this.loading = false;
      });
  },
  methods: {
    getListWay() {
      this.loading = true;
      getplatformAddressList(this.searchForm).then((res) => {
        if (res.code !== 200 || res.status !== 1) {
          this.loading = false;
          return this.$messages.error(res.msg);
        }
        this.AddressList = res.data.list;
        this.total = res.data.total;
        this.loading = false;
      });
    },
    resetting() {
      this.searchForm = {
        supplier_id: "", // 供应商id
        recipient: "", // 收货人姓名
        phone_number: "", // 手机号
        is_default: "", // 是否默认 1默认 2不默认
        province_id: "", // 类型 1省 2市 3区
        city_id: "", // 值
        district_id: "", // 值
        page: 1,
        pageSize: 10,
      };
      this.getListWay();
    },
    provinceWay(val) {
      this.searchForm.city_id = "";
      this.searchForm.district_id = "";
      this.provinceList.forEach((item) => {
        if (item.id == val) {
          this.cityList = item.children;
        }
        this.$forceUpdate();
      });
    },
    cityWay(val) {
      this.searchForm.district_id = "";
      this.cityList.forEach((item) => {
        if (item.id == val) {
          this.districtList = item.children;
        }
      });
      this.$forceUpdate();
    },
    addWay() {
      this.addressDialog = true;
    },
    addressClose() {
      this.addressForm = {
        recipient: "",
        phone_number: "",
        province_id: "",
        city_id: "",
        district_id: "",
        address_details: "",
        is_default: 2,
        id: "",
        // supplier_id: "",
      };
      this.addressDialog = false;
      this.$refs.addressForm.resetFields();
    },
    editWay(row) {
      this.addressDialog = true;
      this.addressLoading = true;
      geplatformAddressInfo({ id: row.id, supplier_id: row.supplier_id }).then(
        (res) => {
          if (res.code !== 200 || res.status !== 1) {
            this.addressLoading = false;
            return this.$messages.error(res.msg);
          }
          this.provinceWay(row.province_id);
          this.cityWay(row.city_id);
          this.addressForm = JSON.parse(JSON.stringify(row));

          this.addressLoading = false;
        }
      );
    },
    delWay(row) {
      this.loading = true;
      delplatformAddress({ id: row.id })
        .then((res) => {
          if (res.code !== 200 || res.status !== 1) {
            this.loading = false;
            return this.$messages.error(res.msg);
          }
          this.$messages.success("删除成功");
          this.getListWay();
        })
        .catch((err) => {
          this.loading = false;
          this.$messages.error(err.msg);
        });
    },
    addressSubmit() {
      this.$refs.addressForm.validate((valid) => {
        if (valid) {
          this.addressLoading = true;
          SaveplatformAddress(this.addressForm).then((res) => {
            if (res.code !== 200 || res.status !== 1) {
              this.addressLoading = false;
              return this.$messages.error(res.msg);
            }
            this.$messages.success(res.msg);
            this.addressLoading = false;
            this.addressClose();
            this.addressDialog = false;
            this.getListWay();
          });
        } else {
          return false;
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
/* 输入框 */
.addressInput {
  width: 73%;
  margin-left: 20px;
}

/* 提示 */
.secondTitle {
  width: 100%;
  height: 44px;
  background: rgb(212, 227, 252);
  line-height: 44px;
  padding: 0 15px;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  span {
    font-size: 12px;
    margin-left: 10px;
    color: #333;
    font-weight: bold;
  }
}

/* 按钮 */
.btnGroup {
  width: 100%;
  position: absolute;
  bottom: 20px;
  right: 0;
  display: flex;
  justify-content: flex-end;
  padding-right: 20px;
  box-sizing: border-box;
}
</style>
